<template>
    <el-dialog title="扫码登录" v-model="openQrLogin" width="600px" append-to-body @close="cancel"
        :close-on-click-modal="false">
        <!-- <el-image :src="tinyCodeSrc"></el-image> -->
        <div v-if="openQrLogin">
            <canvas id="canvasQrLogin" :width="560" :height="560"></canvas>
        </div>
    </el-dialog>
</template>
  
<script setup>
import { qrlogin } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import QRCode from "qrcode";

const router = useRouter();
const { proxy } = getCurrentInstance();

const openQrLogin = ref(false);
const tinyCodeSrc = ref(null);
const tiny_str = ref(null);
const data = ref(null);
const timer = ref(null);
// 打开弹窗
function open(row) {
    openQrLogin.value = true;
    tinyCodeSrc.value = null;
    data.value = row.scanid
    getQrcode(row);
}
// 暴露出去
defineExpose({
    open
})

function cancel() {
    openQrLogin.value = false;
    clearInterval(timer.value)
    timer.value = null
}

// 获取二维码
function getQrcode(row) {
    tiny_str.value =
        "https://opr.gtcharger.com?scanid=" + row.scanid;
    createTinyQrcode();
    timer.value = setInterval(() => {
        checkLogin(data.value)
    }, 1000)
}

function checkLogin() {
    qrlogin({ scanid: data.value }).then((response) => {
        if (response.data.scan == 2) {
            setToken(response.data.token)
            cancel()
            router.push({ path: "/" });
        } else if (response.data.scan == -1) {
            getQrcode()
        }
    })
}

// 生成二维码
function createTinyQrcode() {
    QRCode.toDataURL(tiny_str.value, { errorCorrectionLevel: "H" })
        .then((url) => {
            tinyCodeSrc.value = url.replace(/[\r\n]/g, "");
        })
        .catch((err) => {
            ElNotification({
                message: "二维码生成错误" + err,
                type: "error",
            });
            return;
        });
    setTimeout(() => {
        drawQrLogin();
    }, 100);
}

// 绘制二维码
function drawQrLogin() {
    let canvas = document.getElementById("canvasQrLogin");
    let ctx = canvas.getContext("2d"); // 创建画布
    let img = new Image(); // 因为拿不到图片静态资源，所以创建图片标签
    img.setAttribute("crossOrigin", "anonymous"); // 解决图片跨域问题,也要放到赋值前，否贼大部分浏览器会报错
    img.src = tinyCodeSrc.value;
    // 加载图片
    img.onload = () => {
        // 绘制图片
        ctx.drawImage(img, 0, 0, 560, 560);
        // 合成图片
        let imgUrl = canvas.toDataURL("image/jpg");
        tinyCodeSrc.value = imgUrl;
    };
}
</script>
    
<style scoped>
.tiny_qr {
    width: 4.8cm;
}
</style>